package com.newsystem.service.impl;

import com.newsystem.MyUtils.CommonResult;
import com.newsystem.MyUtils.MyUUIDUtils;
import com.newsystem.mapper.NewsMapper;
import com.newsystem.pojo.News;
import com.newsystem.pojo.TGood;
import com.newsystem.mapper.TGoodMapper;
import com.newsystem.service.ITGoodService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.sql.Wrapper;

/**
 * <p>
 * 用户对新闻的点赞 服务实现类
 * </p>
 *
 * @author chenlitao
 * @since 2022-11-06
 */
@Service
public class TGoodService extends ServiceImpl<TGoodMapper, TGood> implements ITGoodService {

    @Autowired
    private TGoodMapper tGoodMapper;
    @Autowired
    private NewsMapper newsMapper;

    //用户给新闻点赞或者取消点赞
    public CommonResult<Object> insertGood(String userId,String newsId){
        News news = newsMapper.selectById(newsId);
        if(news != null){
            TGood tGood = tGoodMapper.selectTGood(userId,newsId);
            if(tGood!=null){
                if(news.getGoodNum()!=null && news.getGoodNum() >0 ){
                    news.setGoodNum(news.getGoodNum()-1);
                }
                else {
                    news.setGoodNum(0);
                }
                if (tGoodMapper.deleteById(tGood.getId()) > 0){
                    newsMapper.updateById(news);
                }
                return CommonResult.failed("取消点赞");
            }
            else {
                if(news.getGoodNum()!=null){
                    news.setGoodNum(news.getGoodNum()+1);
                }
                else {
                    news.setGoodNum(1);
                }
                tGood = new TGood();
                tGood.setId(MyUUIDUtils.getUUID());
                tGood.setUserId(userId);
                tGood.setNewsId(newsId);
                if(tGoodMapper.insert(tGood)>0){
                    newsMapper.updateById(news);
                }
                return CommonResult.success("成功点赞");
            }
        }
        return CommonResult.failed("无此新闻");
    }
}
